import { IImportData, IListItem } from '../interfaces'

export interface IStoreData {
    // 插件配置
    config?: {
        // 是否启用插件
        enabled?: boolean
    }
    // api列表
    list?: IListItem[]
    // 缓存
    cache?: {
        // 导入历史
        importHistory?: {
            mode: IImportData['mode']
            url: string
        }[]
    }
    // 从yapi页面导入，临时存储通信数据
    importFromYapiPage?: {
        recommendGroupName?: string
        apiList?: any[]
    }
}

export type IStoreKey = keyof IStoreData

export const LIST_KEY = 'list'
export const CACHE_KEY = 'cache'
export const CONFIG_KEY = 'config'
export const IMPORT_FROM_YAPI_PAGE_KEY = 'importFromYapiPage'

export const store = {
    async get<K extends IStoreKey>(key: K): Promise<IStoreData[K]> {
        let val = await storage.getItem<any>(`local:${key}`)
        try {
            val = JSON.parse(val)
        } catch {}
        return val
    },
    async set<K extends IStoreKey>(key: K, value: IStoreData[K]) {
        let val: any = value
        try {
            typeof val === 'object' && (val = JSON.stringify(val))
        } catch {}
        await storage.setItem(`local:${key}`, val)
    },
    async remove<K extends IStoreKey>(key: K) {
        await storage.removeItem(`local:${key}`)
    },
}
